/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Accelerometer;

import Communication.Communicator;
import Wasa.Acceleration;
import Wasa.Response;
import Wasa.Type;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author gianmariospacagna
 */
class RealTimeMeasurement extends Thread {

    private Accelerometer sps;
    private CircularArray temp;
    private CircularArray light;
    private Communicator c;
    boolean active;

    public RealTimeMeasurement(Accelerometer ameter, Communicator c, CircularArray light, CircularArray temp) {
        this.sps = ameter;
        this.c = c;
        this.light = light;
        this.temp = temp;
        this.active = false;
    }

    @Override
    public void run() {

        Acceleration acc = null;
        long timestamp1;
        long timestamp2;
        
        Position pos;
        Velocity vel;
        while (true) {
            
            if (active) {
                System.out.println("Timestamp\t\tLatency\t\tVelocity\t\tPosition");
                timestamp1 = System.nanoTime();
                try {
                    acc=c.measureAcceleration();
                } catch (WrongWASADataFormatException ex) {
                    Logger.getLogger(RealTimeMeasurement.class.getName()).log(Level.SEVERE, null, ex);
                }
                timestamp2 = System.nanoTime();
                long timestamp= (long) (0.5*(timestamp1+timestamp2));
                long latency = timestamp2-timestamp1;
                vel=new Velocity(acc);
                pos=new Position(vel);
                
                
                
            }
        }

    }

    public void activate() {
        active = true;
    }

    public void standbye() {
        active = false;
    }

    public CircularArray getLight() {

        return this.light;
    }

    public CircularArray getTemp() {

        return this.temp;
    }

    public void calibrate() {
        calibrateTemp();
        calibrateLight();

    }

    private void calibrateTemp() {

        while (!this.temp.isFull()) {
            Response resp = c.measureTemp();
            System.out.println("Measure T: " + resp.getType() + resp.getMeasure());
            if (resp.getType().compareTo(Type.DATA) == 0) {
                this.temp.addElement(Float.parseFloat(resp.getMeasure()));
            }
        }

    }

    private void calibrateLight() {
        while (!this.light.isFull()) {
            Response resp = c.measureLight();
            System.out.println("Measure L: " + resp.getType() + resp.getMeasure());
            if (resp.getType().compareTo(Type.DATA) == 0) {
                this.light.addElement(Float.parseFloat(resp.getMeasure()));
            }
        }

    }
}
